/**
 * 
 */
package org.mspring.mlog.service.impl;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.mspring.mlog.entity.Album;
import org.mspring.mlog.entity.Photo;
import org.mspring.mlog.service.OptionService;
import org.mspring.mlog.service.PhotoUploadService;
import org.mspring.mlog.utils.UploadUtils;
import org.mspring.platform.spring.BeanFactory;
import org.mspring.platform.utils.Size;
import org.mspring.platform.utils.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 
 * @author Gao Youbo
 * @since 2012-12-11
 */
public abstract class AbstractPhotoUploadService implements PhotoUploadService {

    @Override
    public MultipartFile getPhotoMultipartFile(HttpServletRequest request) {
        // TODO Auto-generated method stub
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        if (fileMap == null || fileMap.size() < 1) {
            return null;
        }
        MultipartFile mf = null;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            mf = entity.getValue();
            break;
        }
        return mf;
    }

    @Override
    public BufferedImage getBufferedImage(MultipartFile mf) {
        // TODO Auto-generated method stub
        try {
            return ImageIO.read(mf.getInputStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String getPhotoSaveName(MultipartFile mf) {
        // TODO Auto-generated method stub
        return UploadUtils.getUniqueFilename() + "." + FilenameUtils.getExtension(mf.getOriginalFilename());
    }

    @Override
    public String getPhotoSavePath(String photoSaveName) {
        // TODO Auto-generated method stub
        StringBuilder sb = new StringBuilder();
        sb.append(UploadUtils.getUploadDirectory(PHOTO_DIRECTORY));
        sb.append(photoSaveName);
        return sb.toString();
    }

    @Override
    public String getPhotoPreviewSavePath(String photoSavePath) {
        // TODO Auto-generated method stub
        photoSavePath = photoSavePath.replace("\\", "/");
        String ext = FilenameUtils.getExtension(photoSavePath);
        String path = StringUtils.substringBeforeLast(photoSavePath, "/");
        String name = photoSavePath.substring(photoSavePath.lastIndexOf("/"), photoSavePath.lastIndexOf("."));
        return path + "/preview" + name + "_preview." + ext;
    }

    @Override
    public String getContentType(MultipartFile mf) {
        // TODO Auto-generated method stub
        return mf.getContentType();
    }

    @Override
    public long getContentLength(MultipartFile mf) {
        // TODO Auto-generated method stub
        return mf.getSize();
    }

    @Override
    public Size getZoomSize(Integer sourceW, Integer sourceH, Integer targetW, Integer targetH) {
        // TODO Auto-generated method stub
        double sx = (double) targetW / sourceW;
        double sy = (double) targetH / sourceH;
        if (sx > sy) {
            sx = sy;
            targetW = (int) (sx * sourceW);
        } else {
            sy = sx;
            targetH = (int) (sy * sourceH);
        }
        return new Size(targetW, targetH);
    }

    @Override
    public boolean isLimitSize(int sourceWidth, int sourceHeight) {
        // TODO Auto-generated method stub
        boolean isLimit = "true".equals(BeanFactory.getBean(OptionService.class).getOption("photo_islimit_size"));
        if (!isLimit) {
            return false;
        }

        Size size = getMaxSize();
        // 原始图片的大小是否超出限定范围
        if (sourceWidth < size.getWidth() && sourceHeight < size.getHeight()) {
            return false;
        }
        return true;
    }

    @Override
    public Size getMaxSize() {
        // TODO Auto-generated method stub
        OptionService optionService = BeanFactory.getBean(OptionService.class);
        String string_ori_width = optionService.getOption("photo_max_width");
        String string_ori_height = optionService.getOption("photo_max_height");
        int MAX_WIDTH = StringUtils.isBlank(string_ori_width) ? DEFAULT_MAX_WIDTH : Integer.parseInt(string_ori_width);
        int MAX_HEIGHT = StringUtils.isBlank(string_ori_height) ? DEFAULT_MAX_HEIGHT : Integer.parseInt(string_ori_height);
        return new Size(MAX_WIDTH, MAX_HEIGHT);
    }

    @Override
    public Photo getPhotoEntity(BufferedImage image, String url, long album, MultipartFile mf, String photoSaveName, String previewUrl) {
        // TODO Auto-generated method stub
        Photo photo = new Photo();
        photo.setWidth(image.getWidth());
        photo.setHeight(image.getHeight());
        photo.setAlbum(new Album(album));
        photo.setName(photoSaveName);
        photo.setUrl(url);
        photo.setPreviewUrl(previewUrl);
        photo.setCreateTime(new Date());
        photo.setSize((int) mf.getSize());
        photo = fillExifInfo(mf, photo);
        return photo;
    }

    @Override
    public Photo fillExifInfo(MultipartFile mf, Photo photo) {
        // TODO Auto-generated method stub
        // IImageMetadata metadata = null;
        // try {
        // metadata = ImageUtils.getMetadataInfo(mf.getInputStream());
        // } catch (IOException e1) {
        // // TODO Auto-generated catch block
        // return photo;
        // }
        //
        // if (metadata == null) {
        // return photo;
        // }
        //
        // try {
        // if (metadata instanceof JpegImageMetadata) {
        // final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
        //
        // TiffField orientation =
        // jpegMetadata.findEXIFValueWithExactMatch(TiffTagConstants.TIFF_TAG_ORIENTATION);
        // if (orientation != null) {
        // photo.setOrientation(orientation.getIntValue());
        // }
        //
        // TiffField manufacturer =
        // jpegMetadata.findEXIFValueWithExactMatch(TiffTagConstants.TIFF_TAG_MAKE);
        // if (manufacturer != null) {
        // photo.setManufacturer(manufacturer.getStringValue());
        // }
        //
        // // ExifTagConstants
        // // TiffTagConstants
        //
        // TiffField model =
        // jpegMetadata.findEXIFValueWithExactMatch(TiffTagConstants.TIFF_TAG_MODEL);
        // if (model != null) {
        // photo.setModel(model.getStringValue());
        // }
        //
        // TiffField aperture =
        // jpegMetadata.findEXIFValueWithExactMatch(ExifTagConstants.EXIF_TAG_APERTURE_VALUE);
        // if (aperture != null) {
        // photo.setAperture(aperture.getStringValue());
        // }
        //
        // TiffField colorSpace =
        // jpegMetadata.findEXIFValueWithExactMatch(TiffTagConstants.TIFF_TAG_COLOR_MAP);
        // if (colorSpace != null) {
        // photo.setColorSpace(colorSpace.getStringValue());
        // }
        //
        // TiffField exposureBias =
        // jpegMetadata.findEXIFValueWithExactMatch(ExifTagConstants.EXIF_TAG_EXPOSURE_MODE);
        // if (exposureBias != null) {
        // photo.setExposureBias(exposureBias.getStringValue());
        // }
        //
        // TiffField focalLength =
        // jpegMetadata.findEXIFValueWithExactMatch(ExifTagConstants.EXIF_TAG_FOCAL_LENGTH);
        // if (focalLength != null) {
        // photo.setFocalLength(focalLength.getStringValue());
        // }
        //
        // TiffField iso =
        // jpegMetadata.findEXIFValueWithExactMatch(ExifTagConstants.EXIF_TAG_ISO);
        // if (iso != null) {
        // photo.setISO(iso.getIntValue());
        // }
        //
        // TiffField shutter =
        // jpegMetadata.findEXIFValueWithExactMatch(ExifTagConstants.EXIF_TAG_SHUTTER_SPEED_VALUE);
        // if (shutter != null) {
        // photo.setShutter(shutter.getStringValue());
        // }
        //
        // TiffField exposureTime =
        // jpegMetadata.findEXIFValueWithExactMatch(ExifTagConstants.EXIF_TAG_EXPOSURE_TIME);
        // if (exposureTime != null) {
        // photo.setExposureTime(exposureTime.getStringValue());
        //
        // }
        // }
        // } catch (ImageReadException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
        return photo;
    }
}
